package jjn.round1;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Jjn
 * @since 2022/9/22 23:44
 */
public class LeetCode77_Combinations {
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> result = new ArrayList<>(n * k);
        backtrack(result, n, k, new ArrayList<>(), 1);
        return result;
    }

    private void backtrack(List<List<Integer>> result, int n, int k, List<Integer> current, int stage) {
        if (current.size() == k) {
            // 必须copy出来一个新的
            result.add(new ArrayList<>(current));
            return;
        }
        if (stage > n) {
            return;
        }
        current.add(stage);
        backtrack(result, n, k, current, stage + 1);
        current.remove(current.size() - 1);
        backtrack(result, n, k, current, stage + 1);
    }
}
